//
//  CustomSlider.swift
//  VSDK
//
//  Created by Ink on 2024-03-15.
//

import UIKit

open class CustomSlider: UISlider {
    
    public var trackRectHeight: CGFloat = 10.0
    
    override open func trackRect(forBounds bounds: CGRect) -> CGRect {
        let defaultBounds = super.trackRect(forBounds: bounds)
        return CGRect(
            x: defaultBounds.origin.x,
            y: defaultBounds.origin.y + defaultBounds.size.height/2 - trackRectHeight/2,
            width: defaultBounds.size.width,
            height: trackRectHeight
        )
    }
    
    //    open override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
    //            // 获取触摸点的位置
    //            let touchPoint = touch.location(in: self)
    //            // 计算滑块的宽度相对于整个滑轨的比例
    //            let sliderWidth = self.bounds.width
    //            let valueRange = CGFloat(self.maximumValue - self.minimumValue)
    //
    //            // 根据触摸点的位置计算新的值
    //            let newValue = (touchPoint.x / sliderWidth) * valueRange + CGFloat(self.minimumValue)
    //            self.setValue(Float(newValue), animated: true)
    //
    //            return true // 开始追踪触摸事件
    //        }
    
    private var initialTouchPoint: CGPoint = .zero // 记录初始触摸点
    private var initialValue: Float = 0            // 记录滑块初始值
    
    // 开始追踪触摸
    open override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
        // 获取触摸点
        initialTouchPoint = touch.location(in: self)
        initialValue = self.value
        
        return true // 开始追踪触摸
    }
    
    // 持续追踪触摸
    open override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
        guard isTracking else { return false }
        
        // 获取触摸移动距离
        let touchPoint = touch.location(in: self)
        let deltaX = Float(touchPoint.x - initialTouchPoint.x)
        
        // 将移动距离转换为滑块值的变化
        let trackRect = self.trackRect(forBounds: self.bounds)
        let valueRange = self.maximumValue - self.minimumValue
        let sliderWidth = Float(trackRect.width)
        
        // 计算新值
        let deltaValue = deltaX / sliderWidth * valueRange
        let newValue = initialValue + deltaValue
        
        // 更新滑块值并限制在范围内
        self.setValue(max(min(newValue, self.maximumValue), self.minimumValue), animated: false)
        self.sendActions(for: .valueChanged) // 通知值变化
        
        return true
    }
}
